#!/usr/bin/env python
# encoding: utf-8
"""
@author:  sherlock
@contact: sherlockliao01@gmail.com
"""

import logging
import os
import sys

sys.path.append('.')

import os
print(os.getcwd())
from contentclassify.engine import DefaultTrainer, default_argument_parser, default_setup, launch
import GPUtil
from contentclassify.config import get_cfg


def main(args):
    cfg = demo_setup(args)
    trainer = DefaultTrainer(cfg)
    # if args.resume:
    #     trainer.resume_or_load(resume=args.resume)
    # else:
    #     Checkpointer(trainer.model).load(cfg.MODEL.WEIGHTS)  # load trained model
    return trainer.train()


def demo_setup(args):
    """
    Create configs and perform basic setups.
    """
    cfg = get_cfg()
    cfg.merge_from_file(args.config_file)
    cfg.merge_from_list(args.opts)
    cfg.freeze()
    default_setup(cfg, args)
    return cfg

if __name__ == "__main__":
    args = default_argument_parser().parse_args()
    print("Command Line Args:", args)
    deviceID = GPUtil.getAvailable(limit=int(args.num_gpus), maxLoad=0.01, maxMemory=0.01)
    print(F'Availabe gpu are {deviceID}, Num of gpus is {args.num_gpus}')
    os.environ["CUDA_VISIBLE_DEVICES"] = ",".join(str(i) for i in deviceID)
    launch(
        main,
        args.num_gpus,
        num_machines=args.num_machines,
        machine_rank=args.machine_rank,
        dist_url=args.dist_url,
        args=(args,),
    )
